package com.csdj.point.service;

import com.csdj.beans.entity.Order;
import com.csdj.beans.entity.Points;
import com.csdj.beans.entity.PointsHis;
import com.csdj.beans.entity.PointsHisExample;
import com.csdj.beans.interfaces.order.IOrderService;
import com.csdj.beans.interfaces.point.IPointService;
import com.csdj.common.constant.OrderConstant;
import com.csdj.point.mapper.PointsHisMapper;
import com.csdj.point.mapper.PointsMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PointService implements IPointService {
    @Resource
    private PointsMapper pointsMapper;
    @Resource
    private PointsHisMapper pointsHisMapper;
    @DubboReference
    private IOrderService orderService;

    private Logger log = LoggerFactory.getLogger("pointservice");
    @Override
    public Points getByUid(int uid) {
        return pointsMapper.selectByPrimaryKey(uid);
    }

    /**
     * 根据订单修改积分情况  修改完成后还要修改订单状态
     * @param order
     * @param type
     * @return
     */
    @Override
    public boolean updateByOrder(Order order, byte type) {
        if(order == null)return false;
        Points points = getByUid(order.getUserId());
        if(points == null){
            log.error("orderId:{} 积分不存在",order.getId());
            return false;
        }
        //保证接口幂等性
        if(checkPointHis(order.getId())){
            log.error("orderId:{} 该订单已经支付完成");
            return false;
        }
        if(pointsMapper.updatePointByOrder(order.getUserId(),order.getPoints(),points.getVersion())>0){
            log.info("orderid:{} 积分扣减成功,修改订单状态",order.getId());
            //添加修改记录
            addHis(order,type);
            order.setStatus(OrderConstant.ORDER_PAID);
            if(orderService.update(order)){
                return true;
            }else{
                //修改订单状态失败， 另作处理
            }
        }else{
            log.error("orderId:{} 积分扣减失败",order.getId());
        }

        return false;
    }

    @Override
    public List<PointsHis> getPointHisListByUid(int uid) {
        return null;
    }

    private boolean addHis(Order order ,byte type){
        PointsHis his = new PointsHis();
        his.setAmount(order.getPoints());
        his.setUid(order.getUserId());
        his.setCreateTm(new Date());
        his.setType(type);
        his.setOrderId(order.getId());
        return pointsHisMapper.insert(his)>0;
    }

    private boolean checkPointHis(int orderId){
        PointsHisExample example = new PointsHisExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        final PointsHis pointsHis = pointsHisMapper.selectOneByExample(example);
        return pointsHis != null;
    }
}
